/**
 * Created by dwt on 2017/11/13.
 */
define([
        'dojo/_base/declare',
        'dijit/_WidgetBase',
        'dijit/_TemplatedMixin',
        'dijit/_WidgetsInTemplateMixin',
        'dojo/dom',
        'dojo/on',
        'dojo/dom-construct',
        'dojo/dom-style',
        'dojo/_base/lang',
        'dojo/html',
        'dojo/dom-style',
        'dojo/topic',
        'esri/geometry/Point',
        'esri/graphic',
        'esri/layers/GraphicsLayer',
        'esri/geometry/Extent',

        'dojo/request/xhr',
        'dojo/i18n!./DzLocate/nls/resource',
        'dojo/text!./DzLocate/templates/DzLocate.html',
        '../helper/GeometryHelper',

        'dijit/form/Button',
        'dijit/form/TextBox',
        'dijit/form/Form',
        'xstyle/css!./DzLocate/css/DzLocate.css'

    ], function (declare, WidgetBase, TemplatedMixin, _WidgetsInTemplateMixin, dom, on, domConstruct, domStyle, lang, html, style, topic,
                 Point, Graphic, GraphicsLayer, Extent, xhr, i18n, DzLocateTemplate, GeometryHelper) {
        return declare([WidgetBase, TemplatedMixin, _WidgetsInTemplateMixin], {
            widgetsInTemplate: true,
            templateString: DzLocateTemplate,
            i18n: i18n,
            GraphicLayer: null,
            currentAddress: '',

            postCreate: function () {
                this.inherited(arguments);
                this.GraphicLayer = new GraphicsLayer();
                this.map.addLayer(this.GraphicLayer);
                topic.subscribe('dzlocate/clear', lang.hitch(this, 'clear'));
            },

            addressChange: function () {
                this.currentAddress = this.addressInput.value;
                console.log("搜索地址：" + this.currentAddress);
            },

            getAddress: function () {
                if (this.map == undefined) {
                    return;
                }

                if (this.currentAddress === undefined || this.currentAddress === "") {
                    alert("请输入搜索地址");
                    return;
                }

                this.clear();

                if (GLOBAL_TOKEN !== '') {
                    var xmlhttp = new XMLHttpRequest();
                    xmlhttp.open('GET', 'http://10.207.204.29:8080/OneMapServer/rest/services/address_p/Transfer?token=' + GLOBAL_TOKEN, false);
                    xmlhttp.withCredentials = true; //withCredentials设置true,让浏览器发送HTTP请求时带上客户端的Cookie
                    xmlhttp.send();

                    //调用WebService的方法
                    xmlhttp.open('POST', 'http://10.207.204.29:8080/OneMapServer/rest/services/address_p/Transfer', true);
                    //以ASCH_AddressSearch方法为例，演示如何构造XML格式的SOAP消息
                    var sr = '<?xml version="1.0" encoding="utf-8"?>' +
                        '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
                        '<SOAP-ENV:Body>' +
                        '<tns:ASCH_AddressSearch xmlns:tns="http://tempuri.org/">' +
                        '<tns:vSearch_word>' + this.currentAddress + '</tns:vSearch_word>' +
                        '<tns:vResult_count>10</tns:vResult_count>' +
                        '</tns:ASCH_AddressSearch>' +
                        '</SOAP-ENV:Body>' +
                        '</SOAP-ENV:Envelope>';

                    //设置RequestHeader中的Content-Type为text/xml;charset=utf-8
                    xmlhttp.setRequestHeader('Content-Type', 'text/xml;charset=utf-8');
                    xmlhttp.send(sr);

                    xmlhttp.onreadystatechange = lang.hitch(this, function () {
                        if (xmlhttp.readyState == 4) {
                            if (xmlhttp.status == 200) {
                                var temp = xmlhttp.responseText;
                                //创建文档对象
                                var parser = new DOMParser();
                                var xmlDoc = parser.parseFromString(temp, "text/xml");
                                //提取数据
                                var results = xmlDoc.getElementsByTagName('Table');
                                if (results.length > 0) {
                                    this.displayMessage('');
                                    //解析结果
                                    var results_obj = [];
                                    for (var i = 0; i < results.length; i++) {
                                        var x = results[i].getElementsByTagName("POINT_X")[0].firstChild.nodeValue;
                                        var y = results[i].getElementsByTagName("POINT_Y")[0].firstChild.nodeValue;
                                        var cls = results[i].getElementsByTagName("CLS")[0].firstChild.nodeValue;
                                        var address = "";
                                        if (cls === '道路') {
                                            address = results[i].getElementsByTagName("ROAD1")[0].firstChild.nodeValue;
                                        } else if (cls === '交叉口') {
                                            address += results[i].getElementsByTagName("ROAD1")[0].firstChild.nodeValue;
                                            address += results[i].getElementsByTagName("ROAD2")[0].firstChild.nodeValue;
                                        } else if (cls === '门牌' || cls === '就近门牌') {
                                            address = results[i].getElementsByTagName("ADDRESS")[0].firstChild.nodeValue;
                                        } else {
                                            address = results[i].getElementsByTagName("POI")[0].firstChild.nodeValue;
                                        }
                                        var temp_obj = new Object();
                                        temp_obj.x = x;
                                        temp_obj.y = y;
                                        temp_obj.address = address;
                                        results_obj.push(temp_obj);
                                    }
                                    this.processResults(results_obj);
                                } else {
                                    this.displayMessage('没有找到相关记录');
                                }
                            }
                        }
                    });
                } else {
                    this.displayMessage('请转换到政务网环境');
                    return;
                }
            },
            clear: function () {
                if (this.map == undefined) {
                    return;
                }
                this.GraphicLayer.clear();
                this.resultsNode.style.display = 'none';
                this.resultsGrid.style.display = 'none';
            },
            displayMessage: function (message) {
                domConstruct.empty(this.resultsNode);
                var temp = '<hr style="margin-top: 5px; margin-bottom: 10px;"/>' + message;
                this.resultsNode.innerHTML = temp;
                this.resultsNode.style.display = 'block';
            },
            processResults: function (results) {
                domConstruct.empty("resultAddress");
                if (!results) {
                    return;
                }

                for (var i = 0; i < results.length; i++) {
                    var tempDom = '';
                    tempDom += '<tr><td>' + (i + 1) + '</td><td style="cursor: pointer;">' + results[i]['address'] + '</td></tr>';
                    // tempDom += '<tr><td>' + results[i]['address'] + '</td>';
                    // tempDom += '<td><button class=".btn">定位</button></td></tr>';
                    var row = domConstruct.toDom(tempDom);
                    on(row, 'click', lang.hitch(this, 'gotoAddress', results[i]['x'], results[i]['y']));
                    domConstruct.place(row, "resultAddress", "last");
                }
                this.resultsGrid.style.display = 'block';
            },
            gotoAddress: function (x, y) {
                var pt = new Point(x, y, this.map.spatialReference);
                var pt_symbol = GeometryHelper.simplePictureMarker();
                this.GraphicLayer.add(new Graphic(pt, pt_symbol));
                this.map.setLevel(7);
                this.map.centerAt(pt);
            }
        });
    }
);